<template>
  <view class="root">
    <view class="main fs-26 fw-500 mt-60 ml-30 mr-30 bgc-fff mb-50 color-666">
      <label @click="chooseImage" class="ai-center jc-center">
        <image
          class="avatar br-circle"
          mode="aspectFill"
          :src="uploadAvatar.src || userInfo.avatar || defaultAvatar"
        />
      </label>
      <view
        v-for="(item, index) in inputModel"
        :key="index"
        class="code-box fd-row height-100 ai-center"
      >
        <text class="mr-12">{{ item.title }}:</text>
        <input
          class="f1 input fs-26 width-0"
          v-model="model[item.model]"
          :maxlength="item.maxlength"
          :type="item.type"
          @input="changeInput(item.title, index)"
          placeholder-class="color-999"
          :placeholder="item.placeholder"
        />
        <button
          v-if="item.title == '验证码'"
          @click="getCode"
          hover-class="btn-hover"
          :disabled="tips.exc"
          class="color-fff fs-26 code-btn br-12"
        >
          {{ tips.text }}
        </button>
      </view>
    </view>
    <view
      hover-class="btn-hover"
      @click="save"
      class="save-btn br-42 fs-36 fw-500"
    >
      保存
    </view>
  </view>
</template>

<script>
  import icons from "@/components/icons";
  export default {
    components: { icons },
    data: () => ({
      userInfo: uni.getStorageSync("userInfo"),
      defaultAvatar: "/static/imgs/default-avatar.png",
      uploadAvatar: { src: "" },
      inputModel: [
        {
          title: "昵称",
          type: "text",
          maxlength: 16,
          placeholder: "请输入昵称",
          model: "nickname",
        },
        {
          title: "姓名",
          type: "text",
          maxlength: 5,
          placeholder: "请输入姓名",
          model: "username",
        },
        // #ifndef MP-WEIXIN
        {
          title: "联系电话",
          type: "number",
          maxlength: 11,
          placeholder: "请输入联系电话",
          model: "tel",
        },
        // #endif
      ],
      tips: { text: "发送验证码", exc: false, count: 60 },
    }),
    computed: {
      model() {
        const { username, nickname, mobile } = this.userInfo;
        return { nickname, username, tel: mobile };
      },
    },
    methods: {
      countDown() {
        let tips = this.tips,
          count,
          timer;
        tips.exc = true;
        tips.text = `${tips.count}s后重试`;
        count = tips.count;
        timer = setInterval((_) => {
          count--;
          tips.text = `${count}s后重试`;
          if (!count) {
            tips.text = `发送验证码`;
            tips.exc = false;
            count = tips.count;
            clearInterval(timer);
          }
        }, 1000);
      },
      getCode() {
        if (this.tips.exc) return;
        uni.isPhoneNumber(this.model.tel)
          ? (this.countDown(),
            uni.fetch("/api/login/sendsms", {
              data: { mobile: this.model.tel },
              success: (res) => uni.showToast({ title: "发送成功" }),
            }))
          : uni.showToast({
              title: "请输入一个正确的手机号",
              icon: "none",
            });
      },
      chooseImage() {
        uni.chooseImage({
          count: 1,
          success: (res) => (this.uploadAvatar.src = res.tempFilePaths[0]),
        });
      },
      changeInput(title, index) {
        if (title == "联系电话") {
          this.model.code = undefined;
          if (this.inputModel.length == index + 1) {
            this.inputModel.push({
              title: "验证码",
              type: "number",
              maxlength: 6,
              placeholder: "请输入验证码",
              model: "code",
            });
          }
          if (this.model.tel == this.userInfo.mobile) {
            this.inputModel.splice(index + 1, 1);
          }
        }
      },
      save() {
        uni.showLoading({ title: "Loding...", mask: true });
        this.uploadAvatar.src
          ? uni.uploadFile({
              url: uni.REQUEST_URL + "/api/file/media",
              filePath: this.uploadAvatar.src,
              name: "file",
              formData: { token: this.userInfo.token },
              success: (uploadFileRes) => {
                this.uploadAvatar.path = JSON.parse(uploadFileRes.data).data.path;
                this.submit();
              },
            })
          : this.submit();
      },
      submit() {
        const { code, nickname, username } = this.model;

        uni.fetch("/api/user/upinfo", {
          data: {
            img: this.uploadAvatar.path,
            username,
            nickname,
            code,
            mobile: this.model.tel,
          },
          success: (res) => {
            uni.setStorageSync("userInfo", {
              ...res,
              token: this.userInfo.token,
            });
            uni.$emit("updateUserInfo", { msg: "更新用户信息" });
            uni.showToast({
              title: "修改成功",
              mask: true,
              duration: 1200,
              success: () => setTimeout(uni.navigateBack, 1200),
            });
          },
        });
      },
    },
  };
</script>

<style>
  .main {
    box-shadow: 0 5rpx 20rpx 0 rgba(151, 166, 192, 0.22);
    border-radius: 20rpx;
    padding: 30rpx 25rpx;
  }

  .bb-eb {
    border-bottom: 1rpx solid #ebebeb;
  }

  .save-btn {
    margin: 90rpx;
    text-align: center;
    justify-content: center;
    padding: 18rpx 0;
    color: #fff;
    background: linear-gradient(90deg, #8ec5fc, #4388e7);
  }
  .avatar {
    width: 156rpx;
    height: 156rpx;
  }

  .code-btn {
    background: #539ff3;
    padding-left: 9px;
    padding-right: 9px;
    line-height: 2;
  }
</style>